<template>
  <el-dialog :title="title" v-model="dialogVisible" width="600px" append-to-body destroy-on-close>
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="供应商名称" prop="supplierName">
        <el-input v-model="form.supplierName" placeholder="请输入供应商名称" />
      </el-form-item>
      <el-form-item label="供应商编码" prop="supplierCode">
        <el-input v-model="form.supplierCode" placeholder="请输入供应商编码" />
      </el-form-item>
      <el-form-item label="联系人" prop="contactName">
        <el-input v-model="form.contactName" placeholder="请输入联系人姓名" />
      </el-form-item>
      <el-form-item label="联系电话" prop="contactPhone">
        <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
      </el-form-item>
      <el-form-item label="联系地址" prop="address">
        <el-input v-model="form.address" placeholder="请输入联系地址" />
      </el-form-item>
      <el-form-item label="电子邮箱" prop="contactEmail">
        <el-input v-model="form.contactEmail" placeholder="请输入电子邮箱" />
      </el-form-item>
      <el-form-item label="合作状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio v-for="dict in statusOptions" :key="dict.value" :label="dict.value">
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="loading">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, watch, defineComponent } from "vue";
import { ElMessage } from "element-plus";
import { addSupplier, updateSupplier } from "@/api/attendance/supplier";

export default defineComponent({
  name: "SupplierForm",
  props: {
    modelValue: {
      type: Boolean,
      required: true
    },
    title: {
      type: String,
      default: ""
    },
    supplier: {
      type: Object,
      required: true
    }
  },
  emits: ["update:modelValue", "success"],
  setup(props, { emit }) {
    // 状态选项
    const statusOptions = [
      { value: "0", label: "合作中" },
      { value: "1", label: "已终止" }
    ];

    // 对话框可见性
    const dialogVisible = ref(props.modelValue);

    // 表单对象
    const form = reactive({
      supplierId: undefined,
      supplierName: "",
      supplierCode: "",
      contactName: "",
      contactPhone: "",
      contactEmail: "",
      address: "",
      status: "0",
      remark: ""
    });

    // 表单校验规则
    const rules = {
      supplierName: [
        { required: true, message: "请输入供应商名称", trigger: "blur" },
        {
          min: 2,
          max: 100,
          message: "供应商名称长度在2到100个字符之间",
          trigger: "blur"
        }
      ],
      supplierCode: [
        { required: true, message: "请输入供应商编码", trigger: "blur" },
        {
          min: 2,
          max: 50,
          message: "供应商编码长度在2到50个字符之间",
          trigger: "blur"
        }
      ],
      contactName: [{ required: true, message: "请输入联系人姓名", trigger: "blur" }],
      contactPhone: [
        { required: true, message: "请输入联系电话", trigger: "blur" },
        {
          pattern: /^1[3-9]\d{9}$/,
          message: "请输入正确的手机号码",
          trigger: "blur"
        }
      ],
      contactEmail: [{ type: "email", message: "请输入正确的邮箱地址", trigger: "blur" }],
      status: [{ required: true, message: "请选择合作状态", trigger: "change" }]
    };

    // 表单实例
    const formRef = ref(null);
    const loading = ref(false);

    // 监听visible变化
    watch(
      () => props.modelValue,
      val => {
        dialogVisible.value = val;
        if (val) {
          initForm();
        }
      }
    );

    // 监听dialogVisible变化
    watch(
      () => dialogVisible.value,
      val => {
        emit("update:modelValue", val);
      }
    );

    // 初始化表单数据
    const initForm = () => {
      if (props.supplier) {
        Object.assign(form, props.supplier);
      }
    };

    // 取消
    const handleCancel = () => {
      dialogVisible.value = false;
    };

    // 提交表单
    const submitForm = async () => {
      if (!formRef.value) return;

      formRef.value.validate(async valid => {
        if (!valid) return;

        try {
          loading.value = true;
          console.log("表单提交数据:", form);

          if (form.supplierId) {
            // 更新
            const res = await updateSupplier(form);
            console.log("更新结果:", res);
            ElMessage.success("修改成功");
          } else {
            // 新增
            const res = await addSupplier(form);
            console.log("新增结果:", res);
            ElMessage.success("新增成功");
          }
          dialogVisible.value = false;
          emit("success");
        } catch (error) {
          console.error("提交失败", error);
          ElMessage.error("提交失败");
        } finally {
          loading.value = false;
        }
      });
    };

    // 初始化
    initForm();

    return {
      dialogVisible,
      formRef,
      form,
      rules,
      loading,
      statusOptions,
      handleCancel,
      submitForm
    };
  }
});
</script>

<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
